package com.xnfh.home.ui.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.View
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.xnfh.common.bean.HomeStatisticsNum
import com.xnfh.common.bean.WeatherDetailBean
import com.xnfh.common.bean.WeatherWarningBean
import com.xnfh.common.provider.HomeServiceProvider
import com.xnfh.framework.base.BaseFragment
import com.xnfh.framework.base.BaseStateObserver
import com.xnfh.framework.ext.dp
import com.xnfh.framework.log.LogUtil
import com.xnfh.framework.toast.TipsToast
import com.xnfh.home.R
import com.xnfh.home.databinding.FragmentHomeLayoutBinding
import com.xnfh.home.imp.AMapLocationImp
import com.xnfh.home.ui.activity.EnclosureFieldActivity
import com.xnfh.home.ui.adapter.WeatherWarningAdapter
import com.xnfh.home.utils.LocationUtil
import com.xnfh.framework.utils.PermissionUtils
import com.xnfh.home.ui.activity.AgriculturalGlActivity
import com.xnfh.home.utils.WeatherHelper.getDayWeatherPic
import com.xnfh.home.utils.WeatherHelper.getWinddirByCode
import com.xnfh.home.viewmodel.HomeViewModel


/**
 * @Description:
 * @Author: ziheng
 * @CreateDate: 2023/11/8 14:34
 * @UpdateUser: ziheng
 * @UpdateDate: 2023/11/8 14:34
 * @UpdateRemark: 更新说明
 */
class HomeFragment : BaseFragment<FragmentHomeLayoutBinding>(),View.OnClickListener {


    private lateinit var viewModel: HomeViewModel
    private lateinit var adapter: WeatherWarningAdapter

    override fun getLayoutID(): Int = R.layout.fragment_home_layout
    override fun initView(view: View, savedInstanceState: Bundle?) {
        mBind.homeSmartLayout.setEnableLoadMore(false)
        mBind.homeSmartLayout.setEnablePureScrollMode(false)//是否启用纯滚动模式
        mBind.homeSmartLayout.setEnableNestedScroll(false)//是否启用嵌套滚动
        adapter = WeatherWarningAdapter()
        mBind.recyclerMessageList.layoutManager = LinearLayoutManager(requireContext())
        mBind.recyclerMessageList.adapter = adapter
        mBind.homeQd.setOnClickListener(this)
        mBind.homeZz.setOnClickListener(this)
        mBind.homeNz.setOnClickListener(this)
        mBind.homeShebei.setOnClickListener(this)

        //默认先不让滑动
        mBind.recyclerMessageList.isNestedScrollingEnabled = false
        //判断scroll是否滑动到了最底部，如果是的话，就让recycleview可以滑动
        mBind.homeNestedScroll.setOnScrollChangeListener(NestedScrollView.OnScrollChangeListener { _, _, _, _, _ ->
            mBind.recyclerMessageList.isNestedScrollingEnabled = isNestedScrollViewAtBottom()
        })

        view.postDelayed({
            //请求权限
            PermissionUtils.openGPS(requireActivity(), object : PermissionUtils.PermissionImp {
                override fun onSuccess(allGranted: Boolean) {
                    LogUtil.e("onSuccess 开启成功了")
                    //请求定位之后，开启定位获取经纬度
                    LocationUtil.startLocation()
                }

                override fun onField() {
                    super.onField()
                    mBind.homeSmartLayout.autoRefresh()
                    LogUtil.e("onSuccess 开启权限失败了")
                }
            })
            //开启读写权限
            PermissionUtils.requestPermissions(requireActivity())
        }, 100)

        //定位完成请求接口
        LocationUtil.initLocation(requireActivity(), object : AMapLocationImp {
            override fun onLocationChanged() {
                LogUtil.e("onLocationChanged 开启成功了")
                //如果定位成功就自动刷新接口
                mBind.homeSmartLayout.autoRefresh()
                //只有定位成功才能刷新天气接口，必须传入经纬度
                viewModel.requestWeather()
            }

            override fun onLocationError() {
                TipsToast.showTips(R.string.str_no_address_permission_tips)
                //如果定位失败就自动刷新接口
                mBind.homeSmartLayout.autoRefresh()
            }
        })

        mBind.homeSmartLayout.setOnRefreshListener {
            Log.e(TAG, "initView: 首次执行不会执行逻辑")
            viewModel.requestWaetherWarning()
            viewModel.requestFiledStatistics()
        }

    }


    override fun observe() {
        viewModel = HomeViewModel()
        //天气接口
        viewModel.weatherRes.observe(this, object : BaseStateObserver<WeatherDetailBean>(null) {
            @SuppressLint("SetTextI18n")
            override fun getRespDataSuccess(it: WeatherDetailBean) {
                super.getRespDataSuccess(it)
                if(it.winddir == null)return
                mBind.homeTqNumber.text = "${it.temp}°"
                mBind.homeTqMessage.text = "${it.condition} | " +
                        "${getWinddirByCode(requireContext(), it.winddir)}${getString(R.string.str_f)}${it.windlevel}${getString(R.string.str_ji)} | " +
                        "${getString(R.string.str_humidness)}${it.humidity}%"
                mBind.homeTqIcon.setImageResource(getDayWeatherPic(it.condition))
            }
        })
        //天气预警
        viewModel.weatherWarningRes.observe(this,
            object : BaseStateObserver<List<WeatherWarningBean>>(null) {
                override fun getRespDataSuccess(it: List<WeatherWarningBean>) {
                    super.getRespDataSuccess(it)
                    if (it.isEmpty()) {
                        adapter.setEmptyView(com.xnfh.common.R.layout.adapter_empty_view)
                    }
                    adapter.setNewInstance(it.toMutableList())
                    mBind.homeSmartLayout.let { smart ->
                        smart.finishRefresh()
                    }
                }

                override fun getRespDataError() {
                    super.getRespDataError()
                    mBind.homeSmartLayout.let { smart ->
                        smart.finishRefresh()
                    }
                }
            })
        //统计的地块面积和地块数量
        viewModel.statisticsNum.observe(this, object : BaseStateObserver<HomeStatisticsNum>(null) {
            override fun getRespDataSuccess(it: HomeStatisticsNum) {
                super.getRespDataSuccess(it)
                mBind.homeMuData.text = it.areaMuSum.toString()
                mBind.homeFieldNum.text = it.fieldNum.toString()
            }
        })
    }

    override fun onClick(v: View?) {
        when(v){
            mBind.homeQd ->{
                EnclosureFieldActivity.start(requireActivity())
            }
            mBind.homeZz ->{
                HomeServiceProvider.toMain(requireContext(),2)
            }
            mBind.homeShebei ->{
                HomeServiceProvider.toMain(requireContext(),3)
            }
            mBind.homeNz ->{
                AgriculturalGlActivity.start(requireContext())
            }
        }
    }

    /**
     * 判断scroll是否滑动到了最底部
     */
    private fun isNestedScrollViewAtBottom(): Boolean {
        val maxScroll = mBind.homeNestedScroll.getChildAt(0).measuredHeight -  mBind.homeNestedScroll.measuredHeight
        return  mBind.homeNestedScroll.scrollY == maxScroll
    }

}